package xframe.ctl;

import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.Action;

import xframe.util.AutoMapper;
import xframe.util.DynamicVar;
import xframe.util.UtilMaster;
import xframe.util.VTLTranslator;
import xframe.util.XMLInMemory;
import xframe.util.XMLQueryException;
import xframe.util.db.Row;

abstract public class XAction extends Action{

    public XAction(){
    }
    
    public Row getRequestInfo(HttpServletRequest request){
        Row reqParam = AutoMapper.getRequest(request);
        AutoMapper.setAttribues(request, reqParam);
        request.setAttribute("request", reqParam);
        return reqParam;
    }
    
    public String getQuery(String index){
        String query = null;
        try
        {
            query = XMLInMemory.get(index);
        }
        catch(XMLQueryException e)
        {
            e.printStackTrace();
        }
        return query;
    }

    public String mappingQuery(HttpServletRequest request, String index){
        String query = null;
        query = VTLTranslator.getDecode(getQuery(index), (HashMap)request.getAttribute("request"));
        return query;
    }

    //!!!!
    public String mappingQuery(HashMap requestMap, String index){
        String query = null;
        query = VTLTranslator.getDecode(getQuery(index), requestMap);
        return query;
    }

    public int simpleExecuteQuery(HttpServletRequest request, String query, String queryName)throws SQLException{
        Statement stmt = null;
        ResultSet rs = null;
        ArrayList LIST = null;
        Row columnIndexRow = new Row();
        boolean rowChecked = true;
        Connection con = (Connection)request.getAttribute("CONNECTION");
        stmt = con.createStatement();
        rs = stmt.executeQuery(query);
        int resultSize = rs.getFetchSize();
        
      //  if(resultSize > 0){
        	
	        ResultSetMetaData rsmt = rs.getMetaData();
	        int columsize = rsmt.getColumnCount();
	        Row row = null;
	        
	        
	        String  encordingFrom ="";
	        String  encordingTo ="";
	        String encordingStr = "";
	        boolean encoding = false;
	    	try {
	    		encoding	=	"true".equalsIgnoreCase(DynamicVar.get("xframe.database.encoding"));
	    		if(encoding){
					encordingTo = UtilMaster.null2Default(DynamicVar.get("xframe.database.encoding.from"),"8859_1");
					encordingFrom = UtilMaster.null2Default(DynamicVar.get("xframe.database.encoding.to"),"KSC5601"); 
	    		}
			} catch (XMLQueryException e1) {
				e1.printStackTrace();
			} 
	    	String param_string ="";
	        
	        LIST = new ArrayList();
	        for(; rs.next(); LIST.add(row)){
	        	row = new Row();
	            for(int i = 1; i < columsize + 1; i++){
	            	param_string = rs.getString(rsmt.getColumnLabel(i));
	            	if(encoding){
		            	if(param_string != null){
		    				try {
		    					//charSet(param_string);
								encordingStr = new String(param_string.getBytes(encordingFrom),encordingTo);
							} catch (UnsupportedEncodingException e) {
								e.printStackTrace();
							}
		    			}else{
		    				encordingStr = null;
		    			}
	            	}else{
	            		encordingStr = param_string;
	            	}
	            	row.put(rsmt.getColumnLabel(i), encordingStr);
	                if(rowChecked)
	                    columnIndexRow.put((new StringBuffer(String.valueOf(i))).toString(), encordingStr);
	            }
	
	            rowChecked = false;
	        }
      //  }else{
      //  	LIST = new ArrayList();
      //  }

        request.setAttribute(queryName, LIST);
        request.setAttribute(queryName + ".COLUMN_LIST", columnIndexRow);
        if(LIST == null) {
        	request.setAttribute(queryName + ".TOTAL", 0+"");
        }else{
        	request.setAttribute(queryName + ".TOTAL", LIST.size()+"");
        }
        
        //System.out.println(queryName + ".TOTAL"+" : "+LIST.size()+"");
        return rs.getRow();
    }
    public static void charSet2(String str_kr) throws UnsupportedEncodingException{
        String charset[] = {"euc-kr", "ksc5601", "iso-8859-1", "8859_1", "ascii", "UTF-8"};
            
        for(int i=0; i<charset.length ; i++){
            for(int j=0 ; j<charset.length ; j++){
                if(i==j) continue;

      //System.out.println(charset[i]+" : "+charset[j]+" :"+new String(str_kr.getBytes(charset[i]),charset[j]));
            }
        }
    }
    public Row simpleExecuteQueryGetOneRowbackup(HttpServletRequest request, String query, String queryName)throws SQLException{
        Statement stmt = null;
        ResultSet rs = null;
        Connection con = (Connection)request.getAttribute("CONNECTION");
        stmt = con.createStatement();
        rs = stmt.executeQuery(query);
        ResultSetMetaData rsmt = rs.getMetaData();
        int columsize = rsmt.getColumnCount();
        Row row  = new Row();;
        row = setDataAndEncoding(rs, rsmt, columsize, row);
        request.setAttribute(queryName, row);
        return row;
    }
    
    public Row simpleExecuteQueryGetOneRow(HttpServletRequest request, String query, String queryName)throws SQLException{
    	Statement stmt = null;
    	ResultSet rs = null;
    	Connection con = (Connection)request.getAttribute("CONNECTION");
    	stmt = con.createStatement();
    	rs = stmt.executeQuery(query);
    	ResultSetMetaData rsmt = rs.getMetaData();
    	int columsize = rsmt.getColumnCount();
    	Row row  = new Row();
    	String param_string ="";
        String  encordingFrom ="";
        String  encordingTo ="";
        String encordingStr = "";
        boolean encoding = false;
    	try {
    		encoding	=	"true".equalsIgnoreCase(DynamicVar.get("xframe.database.encoding"));
    		if(encoding){
				encordingTo = UtilMaster.null2Default(DynamicVar.get("xframe.database.encoding.from"),"8859_1");
				encordingFrom = UtilMaster.null2Default(DynamicVar.get("xframe.database.encoding.to"),"KSC5601"); 
    		}
		} catch (XMLQueryException e1) {
			e1.printStackTrace();
		} 
		
    	if(rs.next())        {
            row = new Row();
            for(int i = 1; i < columsize + 1; i++){
            	param_string = rs.getString(rsmt.getColumnLabel(i));
            	if(encoding){
	            	if(param_string != null){
	    				try {
	    					//charSet(param_string);
							encordingStr = new String(param_string.getBytes(encordingFrom),encordingTo);
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}
	    			}else{
	    				encordingStr = null;
	    			}
            	}else{
            		encordingStr = param_string;
            	}
            	row.put(rsmt.getColumnLabel(i), encordingStr);
            }
        }
    	request.setAttribute(queryName, row);
    	return row;
    }

	private Row setDataAndEncoding(ResultSet rs, ResultSetMetaData rsmt,
			int columsize, Row row) throws SQLException {
		String  encordingFrom ="";
        String  encordingTo ="";
        String encordingStr = "";
        
    	try {
			encordingTo = UtilMaster.null2Default(DynamicVar.get("xframe.database.encoding.from"),"8859_1");
			encordingFrom = UtilMaster.null2Default(DynamicVar.get("xframe.database.encoding.to"),"KSC5601"); 
		} catch (XMLQueryException e1) {
			e1.printStackTrace();
		} 
    	String param_string ="";
        if(rs.next())        {
            row = new Row();
            for(int i = 1; i < columsize + 1; i++){
            	try {
            		param_string = rs.getString(rsmt.getColumnLabel(i));
            		if(param_string != null){
        				encordingStr = new String(param_string.getBytes(encordingFrom),encordingTo);
        			}
        		} catch (UnsupportedEncodingException e) {
        			e.printStackTrace();
        		}
                row.put(rsmt.getColumnLabel(i), encordingStr);
            }
        }
		return row;
	}

    public int simpleExecuteUpdate(HttpServletRequest request, String query, String queryName) throws SQLException{
        Statement stmt = null;
        Connection con = (Connection)request.getAttribute("CONNECTION");
        stmt = con.createStatement();
        int result = stmt.executeUpdate(query);
        request.setAttribute(queryName, (new StringBuffer(String.valueOf(result))).toString());
        return result;
    }

    public int preparedExecuteUpdate(HttpServletRequest request, HashMap requestMap, String preparedIndex[], String query) throws SQLException{
        PreparedStatement psmt = null;
        Connection con = (Connection)request.getAttribute("CONNECTION");
        psmt = con.prepareStatement(query);
        try
        {
            UtilMaster.consoleOut("xframe.console.VTL.preparedParameter.show", "preparedParameter {{");
            for(int i = 0; i < preparedIndex.length; i++)
            {
                UtilMaster.consoleOut("xframe.console.VTL.preparedParameter.show", "[" +i+"] : "+preparedIndex[i]+" : "+  requestMap.get(preparedIndex[i]));
                psmt.setObject(i + 1, requestMap.get(preparedIndex[i]));
            }

            UtilMaster.consoleOut("xframe.console.VTL.preparedParameter.show", "}} preparedParameter");
        }catch(XMLQueryException e){
            e.printStackTrace();
        }
        int returnValue = psmt.executeUpdate();
        psmt.close();
        return returnValue;
    }
}
